package udptest;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Arrays;

/**
 * @author 李泽伟
 */
public class MainTest {
    @Test
    public void clientTest()  {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            String str = new String("客户端发送的数据");
            // 通过DatagramPacket指定发送地址（相当于快递包裹）
            DatagramPacket packet = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getLocalHost(), 9090);
            //DatagramSocket相当于快递员，将包裹发送
            socket.send(packet);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }
    @Test
    public void serverTest() {
        //服务器指定端口
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(9090);
            byte[] buf = new byte[100];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            System.out.println(new String(packet.getData(), 0, packet.getLength()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }
}
